`timescale 1ns / 1ps

module MDU(
    input clk,
    input reset,
    input [31:0] A,
    input [31:0] B,
    input start,
    input [1:0] Mop,
    input MDDst,
    input HLWr,
    output busy,
    output reg [31:0] HI,
    output reg [31:0] LO
);

    reg [3:0] timer;

    initial begin
        HI <= 0;
        LO <= 0;
        timer <= 0;
    end

    always @(posedge clk) begin
        if(reset)begin
            timer <= 0;
            HI <= 0;
            LO <= 0;
        end
        else begin
            if(start) begin
                case(Mop)
                2'b00:begin
                    timer <= 5;
                    {HI, LO} <= {{32{A[31]}}, A} * {{32{B[31]}}, B};
                end
                2'b01:begin
                    timer <= 5;
                    {HI, LO} <= {32'b0, A} * {32'b0, B};
                end
                2'b10:begin
                    timer <= 10;
                    LO <= $signed($signed(A) / $signed(B));
                    HI <= $signed($signed(A) % $signed(B));
                end
                2'b11:begin
                    timer <= 10;
                    LO <= {1'b0, A} / {1'b0, B};
                    HI <= {1'b0, A} % {1'b0, B};                
                end
                endcase
            end
            else if(HLWr) begin
                if(MDDst == 1)  HI <= A;
                else LO <= A;
            end
            else timer <= (timer == 0)? 0 : (timer - 1);
        end
    end

    assign busy = (timer > 0);

endmodule